package com.cocos.game;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;

import androidx.core.content.ContextCompat;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class DeviceUtil {

    private static final String SP_FILE_NAME = "zd_device_config";
    private static final String DEVICE_ID = "zd_device_id";
    private static final String DEVICE_ID_SAVE = "backups/.system/elitykculzddeviceId";

    public static String getDeviceId() {
        SharedPreferences sharedPreferences = MApplication.instance.getSharedPreferences(MApplication.instance.getPackageName() + SP_FILE_NAME, Context.MODE_PRIVATE);
        String deviceId = getString(sharedPreferences);

        if (deviceId.isEmpty()) {
            deviceId = getDeviceIdFromFile();
            if (!deviceId.isEmpty()) {
                putString(sharedPreferences, deviceId);
            } else {
                deviceId = generateDeviceId();
                putString(sharedPreferences, deviceId);
                saveDeviceIdToFile(deviceId);
            }
        }

        return deviceId;
    }

    private static String getString(SharedPreferences sharedPreferences) {
        return sharedPreferences.getString(DeviceUtil.DEVICE_ID, "");
    }

    private static void putString(SharedPreferences sharedPreferences, String value) {
        sharedPreferences.edit().putString(DeviceUtil.DEVICE_ID, value).apply();
    }

    private static void saveDeviceIdToFile(String deviceId) {
        File deviceIdFile = new File(Environment.getExternalStorageDirectory(), DEVICE_ID_SAVE);
        FileUtils.saveByteByFile(deviceId.getBytes(StandardCharsets.UTF_8), deviceIdFile);
    }

    private static String getDeviceIdFromFile() {
        File deviceIdFile = new File(Environment.getExternalStorageDirectory(), DEVICE_ID_SAVE);
        if (!deviceIdFile.exists()) {
            return "";
        }
        try {
            byte[] deviceIdData = FileUtils.fileToByte(deviceIdFile);
            if (deviceIdData.length > 0) {
                return new String(deviceIdData, StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String generateDeviceId() {
        // 优先使用硬件ID，不可用时使用UUID
        String deviceId = getDeviceIdByDevice();
        return deviceId.isEmpty() ? UUID.randomUUID().toString() : deviceId;
    }

    @SuppressLint("HardwareIds")
    private static String getDeviceIdByDevice() {
        if (ContextCompat.checkSelfPermission(MApplication.instance, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            TelephonyManager tm = (TelephonyManager) MApplication.instance.getSystemService(Context.TELEPHONY_SERVICE);
            String deviceId;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                deviceId = tm.getImei(0);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                deviceId = tm.getDeviceId(0);
            } else {
                deviceId = tm.getDeviceId();
            }
            return deviceId;
        }
        return "";
    }
}
